package com.persistence;

import com.util.Constants;
import com.file.FileManager;
import com.util.MySet;
import com.models.User;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * Created by TimeLiar on 2015/9/17.
 * All Hail The King !!!!!!
 */
public enum UserPersistence {
    @SuppressWarnings("unused")
    INSTANCE;
    private final static Set<User> users = new MySet<>();
    static{
        initUserSet();
    }

    /**
     * Read Users from file
     */
    public static void initUserSet(){
        synchronized (users){
            users.clear();
            users.add(Constants.SUPER_USER);
            String jsonString;
            try{
                jsonString = FileManager.readFile(Constants.USER_DATA);
                if(jsonString == null || (!jsonString.startsWith("[") && !jsonString.endsWith("]"))){
                    FileManager.writeFile("[]",Constants.USER_DATA,false);
                    return;
                }
            } catch (Exception e){
                return;
            }
            try {
                JSONArray jsonArray = new JSONArray(jsonString);
                for(int i = 0 ; i < jsonArray.length() ; i ++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    User user = new User();
                    user.setUsername(jsonObject.getString("username"));
                    user.setPassword(jsonObject.getString("password"));
                    try{
                        JSONObject permission =  jsonObject.getJSONObject("permission");
                        Iterator $i = permission.keys();
                        while ($i.hasNext()){
                            String key = $i.next().toString();
                            user.getPermission().put(key,permission.getString(key));
                        }
                    } catch (Exception ignored){}
                    users.add(user);
                }
            } catch (JSONException e) {
                System.err.println(e.getMessage());
                System.exit(0);
            }
        }
    }
    public static void persistence(){
        synchronized (users){
            users.remove(Constants.SUPER_USER);
            try{
                FileManager.writeFile(users, Constants.USER_DATA, false);
            } catch (Exception e){
                users.add(Constants.SUPER_USER);
                return;
            }
            users.add(Constants.SUPER_USER);
        }
    }
    public static Set<User> getUsers(){
        return users;
    }
}
